var vue = new Vue({
    el: '#app',
    watch: {
        'eco.cover.type': function (val, oldVal) {
            // 每当变更类型发生变化时重置表格内的数据、多选框内数据、远程搜索数据
            this.eco.affectedItems = [];
            this.affectedItemsSelected = [];
            this.affectedItems = [];
            this.getWorkflowByChangeType(val);
            this.getLifeCycles(val);
        },
    },
    created: function () {
        var id = this.getQueryString('id');
        var no = this.getQueryString('no');
        var mode = this.getQueryString('mode');
        var searchType = this.getQueryString('search-type');
        var itemId = this.getQueryString('item-id');

        if (mode === 'create') {
            this.isEdit = true;
            this.isCreate = true;
        }

        // tab定位
        this.curTab = location.hash ? location.hash.substr(1) : 'cover';

        if (id || no) {
            this.getEco({id: id, no: no});
        } else {
            this.getWorkflows();
        }

        // 如果存在搜索类型和物件id则直接插入到受影响的物件
        if (searchType && itemId) {
            this.searchType = searchType;
            this.affectedItemsSelected.push(itemId);
            this.insertToAffected();
        }
    },
    computed: {
        isNA: function (value) {
            return function (value) {
                return value || 'N/A';
            };
        },
        changeType: function (typeId) {
            return function (typeId) {
                for (var key in this.workflows) {
                    if (typeId == this.workflows[key].id) {
                        return this.workflows[key].name;
                    }
                }
            }
        },
        // 状态标签情景
        ecoStatusType: function (statusCode) {
            return function (statusCode) {
                var type = 'warning';
                if (statusCode == 1) {
                    type = 'primary';
                } else if (statusCode == 2) {
                    type = 'success';
                } else if (statusCode == -1) {
                    type = 'danger';
                }

                return type;
            }
        },
        // 状态文本
        ecoStatusText: function (statusCode) {
            return function(statusCode) {
                var text = '待评审';
                if (statusCode == 1) {
                    text = '评审中';
                } else if (statusCode == 2) {
                    text = '已发行';
                } else if (statusCode == -1) {
                    text = '已拒绝';
                }

                return text;
            }
        },
        // 获取姓名
        getUserName: function (userId) {
            return function(userId) {
                for (var key in this.users) {
                    if (userId == this.users[key].id) {
                        return this.users[key].nickname;
                    }
                }
            }
        },
        // 生命周期文本
        getLifeCycleName: function (lifeCycles, id) {
            return function (lifeCycles, id) {
                if (id && lifeCycles) {
                    for (var key in lifeCycles) {
                        if (id == lifeCycles[key].id) {
                            return lifeCycles[key].name;
                        }
                    }
                }
            }
        },
        // 变更类型文本
        ecoType: function () {
            for (var key in this.changeTypes) {
                if (this.changeTypes[key].id == this.eco.cover.type) {
                    return this.changeTypes[key].name;
                }
            }
        },
        ecoCoverDesc: function () {
            return this.eco.cover.desc.replace(/\r\n|\n/g, '<br/>');
        }
    },
    data: function () {
        return {
            curTab: 'cover',
            previewIsShow: false,
            previewComponent: 'project',
            previewData: {},
            loadWorkflows: false,
            isEdit: false,
            isCreate: false,
            search: '',
            affectedLoading: false,
            affectedItemsSelected: [],
            appendToAffectedLoading: false,
            users: [],
            currentUser: [],
            workflowProps: {
                value: 'id',
                label: 'name'
            },
            eco: {
                cover: {
                    id: null,
                    no: '',
                    desc: '',
                    status: {
                        code: null,
                        scenes: '',
                        text: ''
                    },
                    reason: '',
                    workflow: [],
                    created_user_id: null,
                    created_at: null,
                    submitted_at: null,
                    released_at: null
                },
                reviews: [],
                affectedItems: [],
                selectedItems: [],
                logs: [],
                rules: [],
                levels: [],
                attachments: [],
                history: [],
                progress: 0,
                authorizedReviewUsers: [],
                currentLevel: []
            },
            auditFormVisible: false,
            audit: {
                result: 1,
                comment: '',
                extra: false,
                reviewer: null
            },
            uploadData: {},
            fileCount: 0,
            fileUploadSuccessCount: 0,
            affectedItems: [],
            workflows: [],
            searchType: '',
            changeTypes: [],
            workflowName: '',
            files: []
        }
    },
    methods: {
        uploadChange: function (file, fileList) {
            this.fileCount = fileList.length;
        },
        removeFile: function (file, fileList) {
            this.fileCount = fileList.length;
        },
        uploadSuccess: function (response, file, fileList) {
            if (response.data.length) {
                this.eco.attachments.push(response.data);
            }
            this.fileUploadSuccessCount++;

            if(this.fileCount == this.fileUploadSuccessCount) {
                this.$notify.success({
                    title: '提示',
                    message: '保存成功',
                    showClose: false
                });
                var timeout = function (id) {
                    location.replace('/ECO/show?id=' + id);
                };
                setTimeout(timeout(this.uploadData.id), 1000);
            }
        },
        // 按钮组显示逻辑
        isVisible: function(type) {
            var isDisable = true;

            switch(type) {
                case 'submit':
                    if (!this.isEdit && this.eco.cover.status.code == 0 && this.eco.cover.created_user_id == this.currentUser.id) {
                        isDisable = false;
                    }
                    break;

                case 'retract':
                    if (!this.isEdit && this.eco.cover.status.code == 1 && this.eco.cover.created_user_id == this.currentUser.id) {
                        isDisable = false;
                    }
                    break;

                case 'destroy':
                    if (!this.isEdit && this.eco.cover.status.code < 1 && this.eco.cover.created_user_id == this.currentUser.id) {
                        isDisable = false;
                    }
                    break;

                case 'edit':
                    if (!this.isEdit && this.eco.cover.status.code <= 0 && this.eco.cover.created_user_id == this.currentUser.id) {
                        isDisable = false;
                    }
                    break;
            }

            return isDisable;
        },
        deleteAttachment: function(attachment, key) {
            this.$confirm('您确定要删除该文件吗？', '提示', {
                type: 'warning'
            }).then(function() {
                this.$http.post('/ECO/destroyAttachment', {
                    attachment: attachment
                }, {emulateJSON: true}).then(function(res) {
                    if (!res.data.code) {
                        this.eco.attachments.splice(key, 1);
                    }
                    this.$notify({
                        title: '提示',
                        message: res.data.msg,
                        type: res.data.code ? 'danger' : 'success'
                    });
                });
            }).catch(function() {});
        },
        review: function() {
            const loading = this.$loading({lock: true});
            this.$http.post('/ECO/handleEco', {
                action: 'audit',
                data: this.eco.cover,
                audit: this.audit
            }, {emulateJSON: true}).then(function(res) {
                this.$notify({
                    type: res.data.code ? 'error' : 'success',
                    title: '提示',
                    message: res.data.msg
                });

                if (!res.data.code) {
                    setTimeout(function() {
                        if (res.data.data.id) {
                            location.replace('/ECO/show?id=' + res.data.data.id);
                        } else {
                            location.href = '/ECO';
                        }
                    }, 1000);
                } else {
                    loading.close();
                }
            });
        },
        submit: function() {
            var _this = this;
            this.$confirm('发起评审后将不能再修改，确定要发起评审吗？', '提示', {
                type: 'warning',
                center: true
            }).then(function() {
                _this.handleEco('submit');
            }).catch(function() {});
        },
        retract: function() {
            var _this = this;
            this.$confirm('撤回后评审将终止且评审记录将会被清除，确定要撤回吗？', '提示', {
                type: 'warning',
                center: true
            }).then(function() {
                _this.handleEco('retract');
            }).catch(function() {});
        },
        destroy: function() {
            var _this = this;
            this.$confirm('删除后将无法在恢复，确定要删除吗？', '提示', {
                type: 'warning',
                center: true
            }).then(function() {
                _this.handleEco('destroy');
            }).catch(function() {});
        },
        handleEco: function (action) {
            var _this = this;
            const loading = this.$loading({lock: true});
            this.$http.post('/ECO/handleEco', {
                action: action,
                data: this.eco.cover
            }, {emulateJSON: true}).then(function(res) {
                if (res.data.code) {
                    _this.$notify.error({
                        title: '提示',
                        message: res.data.msg
                    });
                    loading.close();
                } else {
                    _this.$notify.success({
                        title: '提示',
                        message: res.data.msg
                    });
                    setTimeout(function() {
                        if (res.data.data.id) {
                            location.replace('/ECO/show?id=' + res.data.data.id);
                        } else {
                            location.href = '/ECO';
                        }
                    }, 1000);
                }
            });
        },
        // 工作流程合并列
        mergeColumn: function (obj) {
            if (obj.columnIndex === 0) {
                return {
                    rowspan: obj.row.level.rowspan,
                    colspan: 1
                };
            }
        },
        workflowChange: function (val) {
            this.$http.post('/ECO/workflowChange', {
                workflow: val
            }, {emulateJSON: true}).then(function (res) {
                if (!res.code) {
                    this.eco.rules = res.data.data;
                }
            });
        },
        // 选中项
        handleSelectionChange: function (val) {
            this.eco.selectedItems = val;
        },
        // 移除选中项
        removeAffectedItems: function () {
            for (var key in this.eco.selectedItems) {
                for (var index in this.eco.affectedItems) {
                    if (this.eco.selectedItems[key].type == this.eco.affectedItems[index].type
                        && this.eco.selectedItems[key].item_id == this.eco.affectedItems[index].item_id) {
                        this.eco.affectedItems.splice(index, 1);
                    }
                }
            }
        },
        // 编辑受影响的物件
        editAffectedItem: function () {

        },
        // 工作流程
        getWorkflows: function () {
            this.$http.post('/ECO/getWorkflows').then(function (res) {
                this.workflows = res.data.data;
            });
        },
        // 获取生命周期列表
        getLifeCycles: function (typeId) {
            this.$http.post('/ECO/getLifeCycles', {
                typeId: typeId
            }, {emulateJSON: true}).then(function (res) {
                this.lifeCycles = res.data.data;
            });
        },
        // 根据变更类型获取工作流
        getWorkflowByChangeType: function (categoryId) {
            this.loadWorkflows = true;
            this.$http.post('/ECO/getWorkflowByChangeType', {
                category_id: categoryId
            }, {emulateJSON: true}).then(function (response) {
                if (response.data.code) {
                    this.$notify.error({
                        title: '提示',
                        message: response.data.msg,
                        showClose: false
                    });
                    this.loadWorkflows = false;
                } else {
                    this.workflows = response.data.data;
                    this.loadWorkflows = false;
                }
            });
        },
        // 根据变更类型获取受影响的物件列表
        getAffectedItemsByChangeType: function (query) {
            if (!this.searchType) return;
            this.affectedLoading = true;
            this.$http.post('/ECO/getAffectedItemsByChangeType', {
                searchType: this.searchType,
                search: query
            }, {emulateJSON: true}).then(function (response) {
                if (response.data.code) {
                    this.affectedLoading = false;
                    this.$notify.error({
                        title: '错误',
                        message: response.data.msg,
                        showClose: false
                    });
                } else {
                    this.affectedLoading = false;
                    this.affectedItems = response.data.data;
                }
            });
        },
        // 获取地址栏参数
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r!=null) return  unescape(r[2]); return null;
        },
        // 切换tab页，高亮显示当前tab
        changeTab: function (tab) {
            this.curTab = tab.name;
            location.hash = tab.name;
        },
        affectedItemSelected: function () {

        },
        // 将受影响的物件添加至表格内
        insertToAffected: function () {
            if (this.affectedItemsSelected.length) {

                this.$http.post('/ECO/getItemsOfAffected', {
                    searchType: this.searchType,
                    itemIds: this.affectedItemsSelected
                }, {emulateJSON: true}).then(function(res) {
                    if (res.data.code) {
                        this.$notify.error({
                            title: '错误',
                            message: res.data.msg,
                            showClose: false
                        });
                    } else {
                        var number = '';
                        var isRepeat = false;

                        if (this.eco.affectedItems.length) {
                            for (var key in res.data.data) {
                                for (var index in this.eco.affectedItems) {
                                    if (res.data.data[key].type == this.eco.affectedItems[index].type
                                        && res.data.data[key].item_id == this.eco.affectedItems[index].item_id) {
                                        number = res.data.data[key].number;
                                        isRepeat = true;
                                        break;
                                    }
                                }
                            }

                            if (isRepeat) {
                                setTimeout(function() {
                                    this.$notify.warning({
                                        title: '提示',
                                        message:  number + '已存在',
                                        showClose: false
                                    });
                                }, 50);

                                return;
                            }
                        }

                        this.eco.affectedItems = this.eco.affectedItems.concat(res.data.data);

                        // 插入后清空
                        this.affectedItemsSelected = [];
                        this.affectedItems = [];
                    }
                });
            } else {
                this.$notify.warning({
                    title: '提示',
                    message: '没有需要添加的物件',
                    showClose: false
                });
            }
        },
        // array_column
        array_column: function (array, field) {
            var arr = [];
            for (var key in array) {
                arr.push(array[key][field]);
            }

            return arr;
        },
        // 保存eco
        saveEco: function () {
            var workflow = this.eco.rules;

            // 表单验证
            if (!this.eco.cover.desc) {
                this.$message.warning('变更描述不能为空');
                return;
            }
            if (!this.eco.cover.reason) {
                this.$message.warning('变更原因不能为空');
                return;
            }
            if (!this.eco.cover.workflow.length) {
                this.$message.warning('请选择工作流程');
                return;
            }
            if (!this.eco.affectedItems.length) {
                this.$message.warning('受影响物件不能为空');
                return;
            }
            if (workflow.length) {
                for (var key in workflow) {
                    if (!workflow[key].selected.length) {
                        this.$message.warning(workflow[key].name + '不能为空');
                        return false;
                    }
                }
            } else {
                this.$message.warning('评审人不能为空');
                return false;
            }

            // 重新整理workflow
            for (var k in workflow) {
                delete workflow[k].group
            }

            const loading = this.$loading({lock: true});

            this.$http.post('/ECO/store', {
                cover: this.eco.cover,
                items: this.eco.affectedItems,
                workflow: workflow
            }, {emulateJSON: true}).then(function (res) {
                if (!res.data.code) {
                    this.uploadData.id = res.data.data.id;
                    if(this.fileCount) {
                        this.$refs.upload.submit();
                    } else {
                        this.$notify.success({
                            title: '提示',
                            message: '保存成功',
                            showClose: false
                        });
                        var timeout = function(id) {
                            location.replace('/ECO/show?id=' + id);
                        };
                        setTimeout(timeout(this.uploadData.id), 1500)
                    }
                } else {
                    loading.close();
                    this.$notify.error({
                        title: '提示',
                        message: res.data.msg,
                        showClose: false
                    });
                }
            });
        },
        getEco: function (params) {
            this.$http.post('/ECO/getEco', params, {emulateJSON: true})
                .then(function (res) {
                    var _this = this;
                    if (res.data.code) {
                        this.$notify.warning({
                            title: '提示',
                            message: res.data.msg,
                            showClose: false
                        });
                    } else {
                        this.changeTypes = res.data.data.changeTypes;
                        this.eco.cover = res.data.data.cover;
                        this.eco.affectedItems = res.data.data.affectedItems;
                        this.workflows = res.data.data.workflows;
                        this.eco.reviews = res.data.data.reviews;
                        this.eco.logs = res.data.data.logs;
                        this.eco.rules = res.data.data.rules;
                        this.eco.levels = res.data.data.levels;
                        this.eco.progress = res.data.data.progress;
                        this.eco.attachments = res.data.data.attachments;
                        this.eco.history = res.data.data.history;
                        this.currentUser = res.data.data.currentUser;
                        this.eco.authorizedReviewUsers = res.data.data.authorizedReviewUsers;
                        this.eco.currentLevel = res.data.data.currentLevel;
                        this.users = res.data.data.users;
                        var getWorkflowName = function (workflows, index, arr) {
                            _this.getWorkflowName(workflows, index, arr);
                        };
                        this.$nextTick(getWorkflowName(this.workflows, 0, []));
                    }
                });
        },
        getWorkflowName: function (workflows, index, arr) {
            if (this.eco.cover.workflow[index]) {
                for (var key in workflows) {
                    if (workflows[key].id == this.eco.cover.workflow[index]) {
                        arr.push(workflows[key].name);
                        this.getWorkflowName(workflows[key].children, index + 1, arr);
                    }
                }
            } else {
                this.workflowName = arr.join(' / ');
            }
        },
        handleCommand(command) {
            this.$notify.warning({
                title: '提示',
                message: '暂不支持该操作',
                showClose: false
            });
        },
        previewItem: function(type, id) {
            this.$http.post('/ECO/previewItem', {
                type: type,
                id: id
            }, {emulateJSON: true}).then(function(response) {
                if (!response.data.code) {
                    this.previewIsShow = true;
                    this.previewData = response.data.data;
                }
            });
        },
    }
});